package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/validatecode")
@Slf4j
public class ValidateCodeController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 体检预约发送验证码
     * @param telephone
     * @return
     */
    @PostMapping("/send4Order")
    public Result send4Order(String telephone){
        try {
            // 随机生成6位验证码
            Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
            String codeStr = validateCode.toString();

            System.out.println(codeStr);

            // 将验证码保存到Redis
            redisTemplate.opsForValue().set(telephone + RedisMessageConstant.SENDTYPE_ORDER,codeStr,5, TimeUnit.MINUTES);

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS,codeStr);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @GetMapping("/send4Login")
    public Result send4Login(String telephone){
        try {
            // 随机生成6位验证码
            Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
            String codeStr = validateCode.toString();
            System.out.println(codeStr);
            // 将验证码保存到Redis
            redisTemplate.opsForValue().set(telephone + RedisMessageConstant.SENDTYPE_LOGIN,codeStr,5, TimeUnit.MINUTES);

            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS,codeStr);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
